package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingcartMapper shoppingcartMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    //用户下单
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersCancelDTO) {
        //查询用户的订单收货地址(校验地址是否为空)
        AddressBook addressBook = addressBookMapper.getById(ordersCancelDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户的购物车数据(校验是否为null)
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingcartMapper.selectByCondition(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表中添加一条数据
        //构建订单实体类对象
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());//订单所属用户
        orders.setNumber(UUID.randomUUID().toString());//订单号
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态:待付款
        orders.setPayStatus(Orders.UN_PAID);//订单支付状态:未支付
        orders.setOrderTime(LocalDateTime.now());//订单时间
        orders.setPhone(addressBook.getPhone());//订单手机号
        orders.setAddress(addressBook.getDetail());//订单收货地址
        orders.setConsignee(addressBook.getConsignee());//订单收货人

        //拷贝一下
        BeanUtils.copyProperties(ordersCancelDTO, orders);//将前段传递的参数拷贝到订单对象中
        //添加订单数据
        orderMapper.insert(orders);
        //向订单表中添加多条订单明细数据
        //将购物车中的商品信息 存储到订单明细表中
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (ShoppingCart shoppingCart1 : shoppingCartList) {
            //构建一个订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        //批量添加订单明细集合数据
        orderDetailMapper.insertBatch(orderDetails);

        //清空当前用户的购物车数据
        shoppingcartMapper.deleteById1(BaseContext.getCurrentId());
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }

    //分页查询订单
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.historyOrders(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long id = orders.getId();// 订单id
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
                OrderVO orderVO = new OrderVO();
                //封装到OrderVO中
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                //再添加到orderVOList集合中
                orderVOList.add(orderVO);
            }
        }
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }

    //根据id查询订单
    @Override
    public OrderVO querById(Long id) {
        //根据id查询订单信息
        Orders orders = orderMapper.querById(id);
        //查询订单对应的菜品信息
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orders.getId());
        //将该订单及其详情封装到Ordervo返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(byOrderId);
        return orderVO;
    }

    //取消订单
    @Override
    public void cancel(Long id) {
        //根据id查询订单详情
        Orders orders = orderMapper.querById(id);
        //校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //校验订单状态能否取消 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //都符合则更新订单状态取消订单
        orders.setCancelReason("用户取消");//用户取消原因
        orders.setCancelTime(LocalDateTime.now());//订单取消时间
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    //再来一单
    @Override
    public void repetition(Long id) {
        //根据订单ID查询当前的订单详情
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(id);
        Long userId = BaseContext.getCurrentId();
        //将订单详情对象转换成购物车对象
        ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : byOrderId) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCarts.add(shoppingCart);
        }
        // 将购物车对象批量添加到数据库
        shoppingcartMapper.insertBatch(shoppingCarts);

    }

    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = Orders.TO_BE_CONFIRMED;
        Integer confirmed = Orders.CONFIRMED;
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    //接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //订单状态 1待付款 2待接单 3 已接单 4 派送中 5 已完成 6 已取消 7 退款
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    //拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据id查询一下订单状态
        Orders orders = orderMapper.querById(ordersRejectionDTO.getId());
        //订单状态 1待付款 2待接单 3 已接单 4 派送中 5 已完成 6 已取消 7 退款
        //判断订单是否已经存在且只为2才可以拒单
        if (orders == null || orders.getStatus() != 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //封装订单对象 设置一下订单状态 修改订单数据
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }

    //派送
    @Override
    public void delivery(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.querById(id);
        //校验订单是否存在 并且状态是3已付款
        if (orders == null || orders.getStatus() != 3) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //封装订单对象 设置一下订单状态 修改订单数据 修改为4 派送中
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders1);

    }
    //完成

    @Override
    public void complete(Long id) {
        //根据id查询订单信息
        Orders orders = orderMapper.querById(id);
        //校验订单是否存在 并且状态是4派送中
        if (orders == null || orders.getStatus() != 4) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //封装订单对象 设置订单为已完成
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.COMPLETED);
        orders1.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }

    //用户催单
    @Override
    public void reminder(Long id) {
    //查询订单是否存在
        Orders orders = orderMapper.querById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于websocket催单
        Map param = new HashMap<>();
        param.put("type", 2);//消息类型 2表示催单
        param.put("orderId", orders.getId());//获取订单号 存入map
        param.put("content", "麻溜的接单!");
        webSocketServer.sendToAllClient(JSONObject.toJSONString(param));
    }
}
